﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace My.Utils
{
    public class StringText
    {
        public static string CutString(string str, int length)
        {
            string temp = str;
            int j = 0;
            int k = 0;
            for (int i = 0; i < temp.Length; i++)
            {
                if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
                {
                    j += 2;
                }
                else
                {
                    j += 1;
                }
                if (j <= length)
                {
                    k += 1;
                }
                if (j >= length)
                {
                    return temp.Substring(0, k);
                }
            }
            return temp;


        }


        public static bool IsNumber(string str)
        {
            if (str != null && Regex.IsMatch(str, @"^-?\d+$"))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public static bool IsEmail(string pageContent)
        {
            string pattern = @"[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}";
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern, RegexOptions.IgnoreCase);
            Match m = regex.Match(pageContent);
            if (m.Success)
            {
                return true;
            }
            else {
                return false;
            }
        }

        public static string Html2Text(string html){
            
            MatchCollection mc = Regex.Matches(html, @"(?<=<(?!a)[^>]*>|^)(?!\s+<)[^<>]+(?=<(?!/a)[^>]*>|$)", RegexOptions.IgnoreCase);
            string result=string.Empty;
            foreach (Match m in mc)
            {
                result += m.Value;
            }
            return result;
        }
    }
}
